<template>
  <view class="scan-code">
    <wd-button block :type="type" :round="round" v-if="showButton">
      {{ buttonText }}
    </wd-button>
  </view>
</template>

<script setup lang="ts">
// import { defineEmits, defineProps } from 'vue'
import type { PropType } from 'vue'

type ButtonType = 'primary' | 'success' | 'warning' | 'error'

const props = defineProps({
  showButton: {
    type: Boolean,
    default: false,
    required: false,
  },
  buttonText: {
    type: String,
    default: '开始扫描',
    required: false,
  },
  round: {
    type: Boolean,
    default: false,
    required: false,
  },
  type: {
    type: String as PropType<ButtonType>,
    default: 'primary',
    required: false,
  },
})

const emit = defineEmits(['scanSuccess'])

function utf8ByteToUnicodeStr(utf8Bytes) {
  let unicodeStr = ''
  for (let pos = 0; pos < utf8Bytes.length; ) {
    const flag = utf8Bytes[pos]
    let unicode = 0
    if (flag >>> 7 === 0) {
      unicodeStr += String.fromCharCode(utf8Bytes[pos])
      pos += 1
    } else if ((flag & 0xfc) === 0xfc) {
      unicode = (utf8Bytes[pos] & 0x3) << 30
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 24
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 18
      unicode |= (utf8Bytes[pos + 3] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 4] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 5] & 0x3f
      unicodeStr += String.fromCodePoint(unicode)
      pos += 6
    } else if ((flag & 0xf8) === 0xf8) {
      unicode = (utf8Bytes[pos] & 0x7) << 24
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 18
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 3] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 4] & 0x3f
      unicodeStr += String.fromCodePoint(unicode)
      pos += 5
    } else if ((flag & 0xf0) === 0xf0) {
      unicode = (utf8Bytes[pos] & 0xf) << 18
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 3] & 0x3f
      unicodeStr += String.fromCodePoint(unicode)
      pos += 4
    } else if ((flag & 0xe0) === 0xe0) {
      unicode = (utf8Bytes[pos] & 0x1f) << 12
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 2] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 3
    } else if ((flag & 0xc0) === 0xc0) {
      // 110
      unicode = (utf8Bytes[pos] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 1] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 2
    } else {
      unicodeStr += String.fromCharCode(utf8Bytes[pos])
      pos += 1
    }
  }
  return unicodeStr
}
interface ScanDeviceConstructor {
  new (): {
    openScan(): void
    setOutScanMode(mode: number): void
    startScan(): void
    stopScan(): void
    closeScan(): void
  }
}
let main
const receiver = ref(null)
const filter = ref(null)
const scanDevice = ref(null)
const ScanDeviceClass = plus.android.importClass(
  'android.device.ScanDevice',
) as unknown as new () => ScanDeviceConstructor

const initScan = () => {
  try {
    main = plus.android.runtimeMainActivity() // 获取activity
    const IntentFilter = plus.android.importClass(
      'android.content.IntentFilter',
    ) as unknown as new () => any
    filter.value = new IntentFilter()
    filter.value.addAction('scan.rcv.message') // 换你的广播动作
    receiver.value = plus.android.implements(
      'io.dcloud.feature.internal.reflect.BroadcastReceiver',
      {
        onReceive: function (context, intent) {
          plus.android.importClass(intent)
          const code = intent.getByteArrayExtra('barocode')
          //	let codeStr = String.fromCharCode(...code);

          const codeStr = utf8ByteToUnicodeStr(code)
          console.log('codeStr:', codeStr)
          scanDevice.value.stopScan() // 停止扫描
          //去除前后空格

          emit('scanSuccess', codeStr.trim())
        },
      },
    )
  } catch (error) {
    console.error('扫描设备初始化异常:', error)
  }
}

const registerScan = () => {
  try {
    main.unregisterReceiver(receiver.value)
  } catch (e) {}
  main.registerReceiver(receiver.value, filter.value)
}
const unregisterScan = () => {
  try {
    main.unregisterReceiver(receiver.value)
  } catch (e) {}
}
const startScan = () => {
  scanDevice.value.stopScan() // 停止扫描
  scanDevice.value.startScan() // 开始扫描
}

// onLoad(() => {
//   console.log('onLoad', '扫码页面加载')

//   scanDevice.value = new ScanDeviceClass()
//   scanDevice.value.openScan() // 打开扫描
//   scanDevice.value.setOutScanMode(0) // 扫描模式

//   //			scanDevice.startScan(); // 开始扫描
//   //			scanDevice.stopScan(); // 停止扫描
//   //			scanDevice.closeScan(); // 关闭扫描

//   initScan()
//   registerScan()
// })
onShow(() => {
  console.log('onLoad', '扫码页面加载')

  scanDevice.value = new ScanDeviceClass()
  scanDevice.value.openScan() // 打开扫描
  scanDevice.value.setOutScanMode(0) // 扫描模式

  //			scanDevice.startScan(); // 开始扫描
  //			scanDevice.stopScan(); // 停止扫描
  //			scanDevice.closeScan(); // 关闭扫描

  initScan()
  registerScan()
})
onHide(() => {
  console.log('onHide', '扫码页面隐藏')
  scanDevice.value?.stopScan()
  scanDevice.value?.closeScan()
  unregisterScan()
  main = null
  scanDevice.value = null
})

onUnload(() => {
  console.log('onUnload', '扫码页面卸载')
  scanDevice.value?.stopScan()
  scanDevice.value?.closeScan()
  unregisterScan()
  main = null
  scanDevice.value = null
})
</script>

<style lang="scss" scoped></style>
